<template>
  <div class="trademark">
    <el-button
      type="primary"
      icon="el-icon-plus"
      @click="showAddOrUpdateTrademark(true)"
      >添加</el-button
    >
    <el-table
      class="trademark-table"
      :data="trademark"
      border
      style="width: 100%"
    >
      <el-table-column type="index" label="序号" width="50"> </el-table-column>
      <el-table-column prop="tmName" label="品牌名称"></el-table-column>
      <el-table-column prop="logoUrl" label="品牌LOGO">
        <template v-slot="{ row }">
          <img class="trademark-img" :src="row.logoUrl" :alt="row.tmName" />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template v-slot="{ row }"
          ><el-button
            type="warning"
            icon="el-icon-edit"
            @click="showAddOrUpdateTrademark(false, row)"
            >修改</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            @click="delTrademark(row)"
            >删除</el-button
          ></template
        >
      </el-table-column>
    </el-table>

    <el-dialog
      :title="`${isAddtrademark ? '添加' : '修改'}品牌`"
      :visible.sync="visible"
    >
      <!-- 表单 -->
      <el-form
        ref="form"
        :rules="rules"
        :model="trademarkForm"
        label-width="100px"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input
            v-model="trademarkForm.tmName"
            class="trademark-input"
          ></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="http://39.98.123.211/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarkForm.logoUrl"
              :src="trademarkForm.logoUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <span>只能上传jpg/png文件，且不超过500kb</span>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateTrademark"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[3, 6, 9, 12]"
      :page-size="pageSize"
      layout="prev,pager,next,jumper,->,sizes,total"
      :total="total"
    >
    </el-pagination>
  </div>
</template>

<script>
import {
  reqGetTrademarkList,
  reqUpdateTrademark,
  reqAddTrademark,
  reqRemoveTrademark,
} from "@api/trademark";
export default {
  name: "trademark",
  data() {
    return {
      trademark: [],
      currentPage: 1,
      pageSize: 3,
      total: 0,
      visible: false,
      isAddtrademark: true,
      trademarkForm: {
        tmName: "",
        logoUrl: "",
      },
      rules: {
        tmName: [{ require: true, validator: this.validator, trigger: "blur" }],
        logoUrl: [
          { require: true, message: "请上传品牌LOGO", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    async getTrademarkList(page, limit) {
      try {
        this.loading = true;
        const res = await reqGetTrademarkList(page, limit);
        this.trademark = res.data.records;
        this.total = res.data.total;
      } catch (e) {
        // console.log(e)
        this.$message.error(e.message || "未知错误");
        this.loading = true;
      }
    },
    addOrUpdateTrademark() {
      this.$refs.form.validate(async (status) => {
        if (status) {
          try {
            const { tmName, logoUrl, id } = this.trademarkForm;
            if (this.isAddtrademark) {
              await reqAddTrademark(tmName, logoUrl);
            } else {
              await reqUpdateTrademark({ tmName, logoUrl, id });
            }
            this.$message.success(
              `{this.isAddtrademark?"添加":"修改"}商品成功`
            );
            this.getTrademarkList(this.currentPage, this.pageSize);
            this.visible = false;
          } catch (e) {
            this.$message.error(e.message || "未知错误");
          }
        }
      });
    },
    showAddOrUpdateTrademark(
      isAdd,
      trademarkForm = { tmName: "", logoUrl: "" }
    ) {
      this.visible = true;
      this.isAddtrademark = isAdd;
      this.trademarkForm = trademarkForm;
      this.$refs.form && this.$refs.form.clearValidate();
    },
    delTrademark(trademark) {
      this.$confirm(
        `您确认要删除 <b style="color: red;">${trademark.tmName}</b> 品牌数据吗?`,
        "提示",
        {
          dangerouslyUseHTMLString: true, // 让内部代码解析成html
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(async () => {
        // 发送请求，删除数据
        await reqRemoveTrademark(trademark.id);

        this.$message({
          type: "success",
          message: "删除品牌数据成功!",
        });

        let { currentPage, pageSize } = this;

        if (this.trademark.length === 1) {
          // 说明之前只有一条数据，并且删除
          currentPage = currentPage - 1 <= 0 ? 1 : currentPage - 1;
          this.currentPage = currentPage;
        }
        // 更新数据
        this.getTrademarkList(currentPage, pageSize);
      });
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.getTrademarkList(this.currentPage, pageSize);
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.getTrademarkList(currentPage, this.pageSize);
    },
    validator(rule, value, callback) {
      console.log(rule, value);
      if (!value) {
        callback("请输入品牌名称");
        return;
      }
      if (value.length < 2 || value.length > 6) {
        callback("请输入2-6位品牌名称");
        return;
      }
      callback();
    },
    handleAvatarSuccess(res) {
      // res 上传成功的响应
      // console.log(res, file);
      if (res.code === 200) {
        this.trademarkForm.logoUrl = res.data;
        return;
      }
      this.$message.error("上传图片失败~");
    },
    beforeAvatarUpload(file) {
      const imagesWhiteList = ["image/jpg", "image/jpeg", "image/png"];
      console.log(file);
      // 判断图片的类型
      const isImageOK = imagesWhiteList.indexOf(file.type) > -1;
      // 判断图片的大小
      const isLt = file.size / 1024 < 500;

      if (!isImageOK) {
        this.$message.error("上传品牌LOGO只能是 JPG 或 PNG 格式!");
      }
      if (!isLt) {
        this.$message.error("上传品牌LOGO大小不能超过 500KB!");
      }
      return isImageOK && isLt;
    },
  },
  mounted() {
    this.getTrademarkList(this.currentPage, this.pageSize);
  },
};
</script>

<style lang="sass" scoped>
.trademark
  padding: 20px
.trademark-table
  margin: 10px 0
.trademark-img
  height: 80px
  weight: 60px
.trademark-input
  width: 350px
</style>
